package commands;

import java.util.ArrayList;

import twitter4j.internal.org.json.JSONArray;
import twitter4j.internal.org.json.JSONException;
import twitter4j.internal.org.json.JSONObject;
import database.models.MessageModel;
import database.objects.Message;

/**
 * Command that gets all the twitter messages interted in the database from the
 * last minute.
 * 
 * @author Project group 9
 * 
 */
public class GetTwitterStreamCommand implements Command {
	JSONObject jsonObject;
	MessageModel messageModel;

	public GetTwitterStreamCommand(JSONObject jsonObject, MessageModel messageModel) {
		this.jsonObject = jsonObject;
		this.messageModel = messageModel;
	}

	@Override
	public String execute() throws JSONException {
		JSONArray sendArray = new JSONArray();

		JSONArray parameters = jsonObject.getJSONArray("getTwitterStream");
		ArrayList<String> keywords = new ArrayList<String>();
		for (int i = 0; i < parameters.length(); i++) {
			keywords.add((String) parameters.get(i));
		}
		
		for (Message mes : messageModel.getTwitterStream(keywords)) {
			JSONObject jMes = new JSONObject();
			JSONObject jOwn = new JSONObject();
			jOwn.put("id", mes.getMessageOwner().getId());
			jOwn.put("twitter_id", mes.getMessageOwner().getTwitterId());
			jOwn.put("name", mes.getMessageOwner().getName());
			jOwn.put("profile_image_url", mes.getMessageOwner().getProfileImageURL());
			
			jMes.put("id", mes.getId());
			jMes.put("text", mes.getText());
			jMes.put("created_at", mes.getCreatedAt());
			jMes.put("place", mes.getPlace());
			jMes.put("owner", jOwn);
			jMes.put("tweet_id", mes.getTweetId());
			jMes.put("is_retweet", mes.getIsRetweet());
			sendArray.put(jMes);
		}

		return sendArray.toString();
	}
}
